import React, { useEffect, useState, useCallback, useRef } from 'react';
import { Platform, PermissionsAndroid, View, Text, StyleSheet, Dimensions, ActivityIndicator, Alert, DimensionValue, TouchableOpacity, Linking, ScrollView, AppState, BackHandler } from 'react-native';
import { MapView, MapType, AMapSdk, Marker } from 'react-native-amap3d';
import Geolocation from '@react-native-community/geolocation';
import NearbyHospitals from './NearbyHospitals';
import Icon from 'react-native-vector-icons/MaterialIcons';

// 添加位置类型定义
interface GeolocationPosition {
  coords: {
    latitude: number;
    longitude: number;
    altitude: number | null;
    accuracy: number;
    altitudeAccuracy: number | null;
    heading: number | null;
    speed: number | null;
  };
  timestamp: number;
}

// 修改位置请求超时时间
const GEOLOCATION_CONFIG = {
  // 适度增加超时时间，避免在信号弱或首次定位时超时
  TIMEOUT: 30000,         // 30秒超时
  HIGH_ACCURACY: true,    // 高精度模式
  MAXIMUM_AGE: 10000,     // 缓存有效期
  DISTANCE_FILTER: 300,   // 位置变化阈值(米)
  TIMEOUT_FALLBACK: 45000, // 45秒备用超时
};

// 修改配置常量
const CONFIG = {
  API_KEY: '5d17e7f70a0d46a9e4ba90f6fbda956f',
  DEFAULT_LOCATION: {
    latitude: 38.814839,
    longitude: 115.489100,
  },
  SEARCH_RADIUS: 5000,
  MAX_HOSPITALS: 3,  // 修改为显示更多医院
  REQUEST_TIMEOUT: 15000,
  LOCATION_THROTTLE: 5000,
  LOCATION_DISTANCE_FILTER: 300,
  POI_TYPES: '090100|090101|090102',
  MAX_RETRIES: 3,
  RETRY_DELAY: 2000,
  LOCATION_TYPE: 1,
  // 高德地图Web服务API
  AMAP_WEB_API: 'https://restapi.amap.com/v5/place/around'
};

// 添加事件类型定义
interface MapStatusChangeEvent {
  nativeEvent: {
    latitude: number;
    longitude: number;
    rotation: number;
    tilt: number;
    zoom: number;
  };
}

// 初始化SDK (只在组件外初始化一次)
let sdkInitialized = false;
try {
  if (!sdkInitialized) {
    AMapSdk.init(
      Platform.select({
        android: CONFIG.API_KEY,
        ios: CONFIG.API_KEY,
      })
    );
    console.log('高德地图 SDK 初始化成功');
    sdkInitialized = true;
  }
} catch (error: any) {
  console.error('高德地图 SDK 初始化失败:', error);
}

// 添加全局错误处理
const ErrorBoundary = (callback: Function): any => {
  try {
    return callback();
  } catch (error) {
    console.error('错误被捕获:', error);
    return null;
  }
};

interface Hospital {
  id: string;
  name: string;
  address: string;
  distance: number;
  phone: string;
  businessHours: string;
  location: {
    latitude: number;
    longitude: number;
  };
  type?: string; // 添加可选的类型属性
}

interface MapContainerProps {
  onError?: () => void;
  mapWidth?: DimensionValue;
  mapHeight?: DimensionValue;
  navigation?: any; // 添加导航对象
}

// 添加计算距离的辅助函数
const calculateDistance = (lat1: number, lon1: number, lat2: number, lon2: number): number => {
  const R = 6371e3; // 地球半径（米）
  const φ1 = lat1 * Math.PI / 180;
  const φ2 = lat2 * Math.PI / 180;
  const Δφ = (lat2 - lat1) * Math.PI / 180;
  const Δλ = (lon2 - lon1) * Math.PI / 180;

  const a = Math.sin(Δφ / 2) * Math.sin(Δφ / 2) +
    Math.cos(φ1) * Math.cos(φ2) *
    Math.sin(Δλ / 2) * Math.sin(Δλ / 2);
  const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));

  return R * c; // 返回米数
};

const MapContainer: React.FC<MapContainerProps> = ({
  onError,
  mapWidth = Dimensions.get('window').width,
  mapHeight = Dimensions.get('window').height * 0.1,
  navigation,
}) => {
  const [mapState, setMapState] = useState({
    loading: true,
    error: null as string | null,
    mapLoaded: false,
    hasPermission: false
  });

  const mapRef = useRef<MapView>(null);
  const isMounted = useRef(true);
  const [mapKey, setMapKey] = useState(0);
  const [userLocation, setUserLocation] = useState<{
    latitude: number;
    longitude: number;
  } | null>(null);
  const [clickedLocation, setClickedLocation] = useState<{
    latitude: number;
    longitude: number;
  } | null>(null);
  const [nearbyHospitals, setNearbyHospitals] = useState<Hospital[]>([]);
  const [debugInfo, setDebugInfo] = useState<string>(''); // 添加调试信息状态
  const appState = useRef(AppState.currentState);
  const watchId = useRef<number | null>(null);
  const requestRef = useRef<AbortController | null>(null);
  const lastFetchTime = useRef(0);
  const requestInProgress = useRef(false);
  const isFirstLocation = useRef(true); // 添加标记，用于追踪是否是首次定位

  // 添加防抖定时器引用
  const moveEndTimerRef = useRef<NodeJS.Timeout | null>(null);

  // 引入更严格的数据保护
  const safeUserLocation = userLocation || CONFIG.DEFAULT_LOCATION;

  // 清理所有资源的函数
  const cleanupResources = useCallback(() => {
    console.log('清理地图资源...');
    // 取消位置监听
    if (watchId.current !== null) {
      try {
        Geolocation.clearWatch(watchId.current);
        watchId.current = null;
      } catch (err) {
        console.error('清理位置监听失败:', err);
      }
    }

    // 取消进行中的请求
    if (requestRef.current) {
      try {
        requestRef.current.abort();
        requestRef.current = null;
      } catch (err) {
        console.error('取消请求失败:', err);
      }
    }

    // 重置标志
    requestInProgress.current = false;
  }, []);

  const updateMapState = useCallback((updates: Partial<typeof mapState>) => {
    if (isMounted.current) {
      setMapState(prev => ({ ...prev, ...updates }));
    }
  }, []);

  // 安全地设置状态
  const safeSetState = useCallback(<T extends any>(setter: React.Dispatch<React.SetStateAction<T>>, value: React.SetStateAction<T>) => {
    if (isMounted.current) {
      setter(value);
    }
  }, []);

  const fetchNearbyHospitals = useCallback(async (latitude: number, longitude: number, forceUpdate = false) => {
    if (requestInProgress.current && !forceUpdate) {
      console.log('忽略重复请求，上一个请求仍在进行中');
      return;
    }

    const now = Date.now();
    if (!forceUpdate && (now - lastFetchTime.current < CONFIG.LOCATION_THROTTLE)) {
      console.log('请求被节流，跳过此次更新');
      return;
    }

    requestInProgress.current = true;
    lastFetchTime.current = now;

    try {
      // 创建新的AbortController用于取消请求
      requestRef.current = new AbortController();

      // 构建高德地图POI搜索请求
      const params = new URLSearchParams({
        key: CONFIG.API_KEY,
        location: `${longitude},${latitude}`, // 高德地图使用经度,纬度的顺序
        radius: CONFIG.SEARCH_RADIUS.toString(),
        types: CONFIG.POI_TYPES, // 医院类型代码
        limit: CONFIG.MAX_HOSPITALS.toString(),
        page_size: CONFIG.MAX_HOSPITALS.toString(), // 添加page_size参数
        offset: CONFIG.MAX_HOSPITALS.toString(), // 添加offset参数
        extensions: 'all' // 返回详细信息
      });

      const response = await fetch(
        `${CONFIG.AMAP_WEB_API}?${params.toString()}`,
        {
          method: 'GET',
          signal: requestRef.current.signal
        }
      );

      if (!response.ok) {
        throw new Error('获取医院数据失败');
      }

      const data = await response.json();

      if (data.status !== '1') {
        throw new Error(data.info || '高德地图API请求失败');
      }

      // 转换高德地图POI数据为我们需要的格式，并确保只取前3条数据
      const hospitals: Hospital[] = data.pois
        .slice(0, CONFIG.MAX_HOSPITALS) // 确保只取指定数量的数据
        .map((poi: any) => {
          const [lng, lat] = poi.location.split(',').map(Number);
          return {
            id: poi.id,
            name: poi.name,
            address: poi.address || '地址未知',
            distance: Number((poi.distance / 1000).toFixed(1)), // 转换为公里
            phone: poi.tel || '暂无电话',
            businessHours: poi.business_hours || '营业时间未知',
            location: {
              latitude: lat,
              longitude: lng
            },
            type: poi.type.split(';')[0] || '医院'
          };
        });

      if (isMounted.current) {
        setNearbyHospitals(hospitals);
        safeSetState<string>(setDebugInfo, `找到 ${hospitals.length} 家医院`);
      }
    } catch (error: any) {
      if (error.name === 'AbortError') {
        console.log('请求被取消');
        return;
      }
      console.error('获取医院失败:', error);
      safeSetState<string>(setDebugInfo, `获取医院失败: ${error.message}`);
    } finally {
      requestInProgress.current = false;
      if (requestRef.current) {
        requestRef.current = null;
      }
    }
  }, [safeSetState, isMounted]);

  const handleNavigate = useCallback((latitude: number, longitude: number) => {
    if (!latitude || !longitude || isNaN(latitude) || isNaN(longitude)) {
      Alert.alert('导航错误', '无效的位置坐标');
      return;
    }

    try {
      if (Platform.OS === 'ios') {
        Linking.openURL(`http://maps.apple.com/?daddr=${latitude},${longitude}`);
      } else {
        Linking.openURL(`geo:${latitude},${longitude}?q=${latitude},${longitude}`);
      }
    } catch (error) {
      console.error('打开导航失败:', error);
      Alert.alert('导航错误', '无法打开地图应用，请手动导航');
    }
  }, []);

  // 应用状态变化监听
  useEffect(() => {
    const subscription = AppState.addEventListener('change', nextAppState => {
      if (nextAppState === 'active' && appState.current !== 'active') {
        // 应用从后台回到前台，重新获取位置和医院
        console.log('应用回到前台，刷新数据');
        if (userLocation) {
          fetchNearbyHospitals(userLocation.latitude, userLocation.longitude);
        }
      } else if (nextAppState === 'background') {
        // 应用进入后台，清理资源
        console.log('应用进入后台，清理资源');
        if (requestRef.current) {
          requestRef.current.abort();
          requestRef.current = null;
        }
      }
      appState.current = nextAppState;
    });

    // 添加返回按钮处理
    const backHandler = BackHandler.addEventListener('hardwareBackPress', () => {
      cleanupResources();
      return false; // 不拦截默认行为
    });

    return () => {
      subscription.remove();
      backHandler.remove();
    };
  }, [cleanupResources, fetchNearbyHospitals, userLocation]);

  // 位置权限请求
  useEffect(() => {
    const requestLocationPermission = async () => {
      try {
        if (Platform.OS === 'android') {
          const granted = await PermissionsAndroid.request(
            PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
            {
              title: "位置权限",
              message: "地图需要访问您的位置",
              buttonNeutral: "稍后询问",
              buttonNegative: "取消",
              buttonPositive: "确定"
            }
          );
          updateMapState({
            hasPermission: granted === PermissionsAndroid.RESULTS.GRANTED,
            loading: false
          });
        } else {
          updateMapState({
            hasPermission: true,
            loading: false
          });
        }
      } catch (err) {
        console.error('获取位置权限失败:', err);
        updateMapState({
          error: "获取位置权限失败",
          loading: false
        });
      }
    };

    requestLocationPermission();

    // 组件卸载时清理
    return () => {
      cleanupResources();
      isMounted.current = false;
    };
  }, [updateMapState, cleanupResources]);

  // 位置监听
  useEffect(() => {
    let isInitialFetchDone = false;
    let positionError = false;
    let fallbackTimeoutId: NodeJS.Timeout | null = null;
    let lastPosition: { latitude: number; longitude: number } | null = null;

    // 添加位置服务降级策略
    const setupLocationFallback = () => {
      fallbackTimeoutId = setTimeout(() => {
        if (!isInitialFetchDone && isMounted.current) {
          console.log('位置服务终极超时，使用默认位置');
          const defaultLocation = CONFIG.DEFAULT_LOCATION;
          safeSetState<{ latitude: number, longitude: number } | null>(setUserLocation, defaultLocation);
          safeSetState<{ latitude: number, longitude: number } | null>(setClickedLocation, defaultLocation);
          fetchNearbyHospitals(defaultLocation.latitude, defaultLocation.longitude, true);
          isInitialFetchDone = true;
          updateMapState({
            loading: false,
            hasPermission: true
          });
          if (mapState.mapLoaded && mapRef.current && isFirstLocation.current) {
            mapRef.current.moveCamera({
              target: defaultLocation,
              zoom: 15
            }, 500);
            isFirstLocation.current = false;
          }
        }
      }, GEOLOCATION_CONFIG.TIMEOUT_FALLBACK);
    };

    const handlePositionUpdate = (position: GeolocationPosition) => {
      if (!isMounted.current) return;

      const { latitude, longitude } = position.coords;
      console.log('位置更新:', { latitude, longitude });

      if (isNaN(latitude) || isNaN(longitude) || latitude === 0 || longitude === 0) {
        console.warn('获取到无效的位置，忽略此次更新');
        return;
      }

      // 检查是否是首次定位或位置有显著变化
      const shouldUpdate = !lastPosition || calculateDistance(
        lastPosition.latitude,
        lastPosition.longitude,
        latitude,
        longitude
      ) > GEOLOCATION_CONFIG.DISTANCE_FILTER;

      if (shouldUpdate) {
        lastPosition = { latitude, longitude };
        safeSetState<{ latitude: number, longitude: number } | null>(
          setUserLocation,
          { latitude, longitude }
        );

        // 只在首次定位时进行医院搜索和地图移动
        if (!isInitialFetchDone) {
          fetchNearbyHospitals(latitude, longitude, true);
          isInitialFetchDone = true;

          // 只在首次定位时移动地图
          if (mapState.mapLoaded && mapRef.current && isFirstLocation.current) {
            mapRef.current.moveCamera({
              target: { latitude, longitude },
              zoom: 15
            }, 500);
            isFirstLocation.current = false;
          }
        }
      }
    };

    if (mapState.hasPermission) {
      console.log('已获取位置权限，开始获取位置');
      try {
        setupLocationFallback();
        // 先高精度尝试
        Geolocation.getCurrentPosition(
          handlePositionUpdate,
          (error) => {
            console.error('高精度定位失败，尝试低精度:', error);
            // 高精度失败后，尝试低精度
            Geolocation.getCurrentPosition(
              handlePositionUpdate,
              (error2) => {
                console.error('低精度定位也失败:', error2);
                positionError = true;
                const defaultLocation = CONFIG.DEFAULT_LOCATION;
                safeSetState<{ latitude: number, longitude: number } | null>(setUserLocation, defaultLocation);
                safeSetState<{ latitude: number, longitude: number } | null>(setClickedLocation, defaultLocation);
                fetchNearbyHospitals(defaultLocation.latitude, defaultLocation.longitude, true);
                isInitialFetchDone = true;
              },
              {
                enableHighAccuracy: false,
                timeout: 8000,
                maximumAge: 20000
              }
            );
          },
          {
            enableHighAccuracy: true,
            timeout: 8000,
            maximumAge: 10000
          }
        );

        // 只在首次定位成功后监听位置变化
        if (!positionError && !watchId.current) {
          watchId.current = Geolocation.watchPosition(
            handlePositionUpdate,
            (error) => {
              console.error('位置监听错误:', error);
            },
            {
              enableHighAccuracy: false,
              timeout: 10000,
              maximumAge: 10000,
              distanceFilter: GEOLOCATION_CONFIG.DISTANCE_FILTER
            }
          );
        }
      } catch (err) {
        console.error('定位服务错误:', err);
        updateMapState({
          error: '定位服务发生错误，使用默认位置',
          loading: false
        });
        if (!isInitialFetchDone) {
          const defaultLocation = CONFIG.DEFAULT_LOCATION;
          safeSetState<{ latitude: number, longitude: number } | null>(setUserLocation, defaultLocation);
          safeSetState<{ latitude: number, longitude: number } | null>(setClickedLocation, defaultLocation);
          fetchNearbyHospitals(defaultLocation.latitude, defaultLocation.longitude, true);
          isInitialFetchDone = true;
        }
      }
    }

    return () => {
      if (fallbackTimeoutId) {
        clearTimeout(fallbackTimeoutId);
      }
      if (watchId.current !== null) {
        try {
          Geolocation.clearWatch(watchId.current);
          watchId.current = null;
        } catch (err) {
          console.error('清理位置监听失败:', err);
        }
      }
    };
  }, [mapState.hasPermission, fetchNearbyHospitals, updateMapState, safeSetState, mapState.mapLoaded]);

  // 地图加载完成处理
  const handleMapReady = useCallback(() => {
    console.log('地图已准备好');

    if (!isMounted.current) return;

    updateMapState({
      loading: false,
      mapLoaded: true,
      error: null
    });

    // 只在首次加载时移动到用户位置
    if (userLocation && isFirstLocation.current) {
      console.log('地图首次加载，移动到用户位置:', userLocation);
      if (mapRef.current) {
        mapRef.current.moveCamera({
          target: userLocation,
          zoom: 15
        }, 500);
        isFirstLocation.current = false;
      }
    }
  }, [updateMapState, userLocation]);

  // 重试处理
  const handleRetry = useCallback(() => {
    if (!isMounted.current) return;

    // 重置地图
    setMapKey(prev => prev + 1);
    updateMapState({
      loading: true,
      error: null,
      mapLoaded: false
    });

    // 重新获取医院数据
    if (userLocation) {
      fetchNearbyHospitals(userLocation.latitude, userLocation.longitude);
    }
  }, [updateMapState, userLocation, fetchNearbyHospitals]);

  // 添加防抖的搜索处理函数
  const debouncedSearch = useCallback((latitude: number, longitude: number) => {
    // 清除之前的定时器
    if (moveEndTimerRef.current) {
      clearTimeout(moveEndTimerRef.current);
    }

    // 设置新的定时器
    moveEndTimerRef.current = setTimeout(async () => {
      try {
        // 更新点击位置用于标记显示
        safeSetState<{ latitude: number, longitude: number } | null>(
          setClickedLocation,
          { latitude, longitude }
        );

        // 获取附近的医院并更新列表
        await fetchNearbyHospitals(latitude, longitude, true);
      } catch (error) {
        console.error('搜索医院失败:', error);
      }
    }, 500); // 500ms 的防抖延迟
  }, [fetchNearbyHospitals, safeSetState]);

  // 清理定时器
  useEffect(() => {
    return () => {
      if (moveEndTimerRef.current) {
        clearTimeout(moveEndTimerRef.current);
      }
    };
  }, []);

  // 错误状态渲染
  if (mapState.error) {
    return (
      <View style={styles.errorContainer}>
        <Text style={styles.errorText}>{mapState.error}</Text>
        <TouchableOpacity
          style={styles.retryButton}
          onPress={handleRetry}
        >
          <Text style={styles.retryButtonText}>重试</Text>
        </TouchableOpacity>
      </View>
    );
  }

  // 主渲染逻辑
  return ErrorBoundary(() => (
    <View style={styles.scrollContent}>
      <View style={styles.container}>
        <View style={styles.mapContainer}>
          <MapView
            key={mapKey}
            ref={mapRef}
            style={[styles.map, { width: mapWidth, height: 300 }]}
            mapType={MapType.Standard}
            initialCameraPosition={{
              target: safeUserLocation,
              zoom: 15
            }}
            myLocationEnabled={true}
            onLoad={handleMapReady}
            onCameraIdle={(event) => {
              try {
                // 获取正确的数据结构
                const { cameraPosition } = event.nativeEvent;
                if (!cameraPosition || !cameraPosition.target) {
                  throw new Error('无法获取相机位置信息');
                }

                const { latitude, longitude } = cameraPosition.target;

                if (!latitude || !longitude) {
                  throw new Error('无法获取有效坐标');
                }

                console.log('视口移动结束，中心点:', { latitude, longitude });

                // 使用防抖处理的搜索函数
                debouncedSearch(latitude, longitude);
              } catch (error) {
                console.error('获取地图中心点失败:', error);
              }
            }}
            onPress={(event) => {
              const { latitude, longitude } = event.nativeEvent;
              if (latitude && longitude) {
                console.log('地图点击位置:', { latitude, longitude });
                safeSetState<{ latitude: number, longitude: number } | null>(
                  setClickedLocation,
                  { latitude, longitude }
                );
                // 点击时立即搜索，不需要防抖
                fetchNearbyHospitals(latitude, longitude, true);
                mapRef.current?.moveCamera({
                  target: { latitude, longitude },
                  zoom: 15
                }, 500);
              }
            }}
          >
            {/* 医院标记 */}
            {nearbyHospitals.map((hospital: Hospital) =>
              hospital && hospital.id ? (
                <Marker
                  key={hospital.id}
                  position={hospital.location}
                  icon={{
                    uri: 'https://a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png',
                    width: 32,
                    height: 32
                  }}
                  onPress={() => {
                    Alert.alert(
                      hospital.name,
                      `地址: ${hospital.address}\n距离: ${hospital.distance}km\n电话: ${hospital.phone}`
                    );
                  }}
                />
              ) : null
            )}
          </MapView>
        </View>
        <View style={styles.clearfix} />
        <NearbyHospitals
          hospitals={nearbyHospitals}
          onNavigate={handleNavigate}
        />
      </View>
    </View>
  ));
};

const styles = StyleSheet.create({
  scrollView: {
    flex: 1,
  },
  scrollContent: {
    flexGrow: 1,
    paddingBottom: 20,
  },
  container: {
    flex: 1,
  },
  mapContainer: {
    height: 290,
    width: '100%',
  },
  map: {
    width: '100%',
    height: 290,
  },
  loadingContainer: {
    position: 'absolute',
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: 'rgba(255, 255, 255, 0.8)',
  },
  loadingText: {
    marginTop: 10,
    fontSize: 14,
    color: '#666',
    textAlign: 'center',
  },
  errorContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    padding: 20,
  },
  errorText: {
    color: 'red',
    marginBottom: 15,
    textAlign: 'center',
  },
  retryButton: {
    backgroundColor: '#007AFF',
    paddingHorizontal: 20,
    paddingVertical: 10,
    borderRadius: 5,
  },
  retryButtonText: {
    color: 'white',
    fontSize: 16,
  },
  clearfix: {
    height: 10,
    width: '100%',
    backgroundColor: 'transparent',
  }
});

export default MapContainer;